
package com.example.demo.controller;

import com.example.demo.bean.ApiResponse;
import com.example.demo.entity.Book;
import com.example.demo.entity.BookType;
import com.example.demo.repository.BookTypeRepository;
import com.example.demo.service.BookTypeService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/bookTypes")
public class BookTypeController {

    private static final Logger logger = LoggerFactory.getLogger(BookController.class);

    @Autowired
    private BookTypeRepository bookTypeRepository;

    @Autowired
    private BookTypeService bookTypeService;

    @GetMapping("/list")
    public ResponseEntity<ApiResponse<List<BookType>>> getAllBooks() {
        List<BookType> bookTypes = bookTypeService.findAll();

        return ResponseEntity.ok(new ApiResponse<>(true, "查询成功", bookTypes));
    }

    @PostMapping("/update")
    public ResponseEntity<ApiResponse<BookType>> updateBookStatus(@RequestBody BookType bookType) {
        try {
            BookType updatedBook = bookTypeService.save(bookType);
            return ResponseEntity.ok(new ApiResponse<>(true, "更新成功", updatedBook));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/delete")
    public ResponseEntity<ApiResponse<BookType>> deleteBookTypeById(@RequestParam("id") int id) {
        try {
            bookTypeService.deleteById(id);
            return ResponseEntity.ok(new ApiResponse<>(true, "删除成功", null));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/search")
    public ResponseEntity<ApiResponse<List<BookType>>> searchByName(@RequestParam("name") String name) {
        try {
            List<BookType> bookTypes = bookTypeService.searchByName(name);
            return ResponseEntity.ok(new ApiResponse<>(true, "搜索成功", bookTypes));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }

}